package com.chen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.common.Constant;
import com.chen.dao.mapper.SysUserMapper;
import com.chen.dao.pojo.SysUser;
import com.chen.service.SysUserService;
import com.chen.util.JWTUtils;
import com.chen.vo.ErrorCode;
import com.chen.vo.Result;
import com.chen.vo.SysUserVo;
import com.chen.vo.param.SysUserParam;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author:chenao
 * @DATE:2022/3/10 22:55
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    private static final String slat = "martins";

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public SysUser findUser(String username, String password) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername,username);
        wrapper.eq(SysUser::getPassword,password);
        return sysUserMapper.selectOne(wrapper);
    }

    @Override
    public Result listSysUser(SysUserParam param) {
        Page<SysUser> page = new Page<>(param.getPage(), param.getLimit());
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        if (Strings.isNotBlank(param.getRole())){
            wrapper.eq(SysUser::getRole,param.getRole());
        }
        //不做非空判断，必须确保数据库不为空值，这里嫌麻烦就不非空判断了
        wrapper.like(SysUser::getUsername,param.getUsername());
        wrapper.like(SysUser::getPhone,param.getPhone());
        sysUserMapper.selectPage(page,wrapper);
        List<SysUserVo> sysUserVoList = new LinkedList<>();
        page.getRecords().stream().forEach(item->{
            SysUserVo sysUserVo = new SysUserVo();
            BeanUtils.copyProperties(item,sysUserVo);
            sysUserVo.setRole(Constant.getname(item.getRole()));
            sysUserVoList.add(sysUserVo);
        });
        return Result.success(sysUserVoList,page.getTotal());
    }

    @Override
    public Result saveSysUser(SysUserParam param) {
        //判断该用户名是否已存在
        if (isExistUserName(param.getUsername())){
            return Result.fail(ErrorCode.ACCOUNT_EXIST.getCode(),ErrorCode.ACCOUNT_EXIST.getMsg());
        }
        SysUser sysUser = new SysUser();
        //加密
        String password = DigestUtils.md5Hex(param.getPassword() + slat);
        sysUser.setPassword(password);
        sysUser.setUsername(param.getUsername());
        sysUser.setRole(param.getRole());
        sysUser.setName(param.getName());
        sysUser.setPhone(param.getPhone());
        //设置用户默认为启用状态
        sysUser.setStatus(Integer.valueOf(Constant.STATUS_OPEN.getvalue()));
        sysUser.setEditTime(new Date().getTime());
        if (Strings.isNotBlank(param.getId())){
            sysUser.setId(param.getId());
            sysUserMapper.updateById(sysUser);
            return Result.successMsg("编辑成功");
        }
        sysUserMapper.insert(sysUser);
        return Result.successMsg("添加成功");
    }

    @Override
    public Result resetSysUserPwd(SysUserParam param) {
        SysUser sysUser = new SysUser();
        //加密
        String password = DigestUtils.md5Hex(Constant.DEFAULT_PASSWORD.getvalue() + slat);
        sysUser.setPassword(password);
        if (Strings.isBlank(param.getId())){
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(),ErrorCode.PARAMS_ERROR.getMsg());
        }
        sysUser.setId(param.getId());
        sysUser.setEditTime(new Date().getTime());
        sysUserMapper.updateById(sysUser);
        return Result.success("resetSuccess");
    }

    @Override
    public Result updateSysUserStatus(SysUserParam param) {
        if (Strings.isBlank(param.getId())&&param.getStatus()==null){
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(),ErrorCode.PARAMS_ERROR.getMsg());
        }
        SysUser sysUser = new SysUser();
        sysUser.setId(param.getId());
        sysUser.setStatus(param.getStatus());
        sysUser.setEditTime(new Date().getTime());
        sysUserMapper.updateById(sysUser);
        return Result.success("ok");
    }

    @Override
    public Result updateSysUserRole(SysUserParam param) {
        SysUser sysUser = new SysUser();
        if (Strings.isBlank(param.getRole()) && Strings.isBlank(param.getId())){
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(),ErrorCode.PARAMS_ERROR.getMsg());
        }
        sysUser.setRole(param.getRole());
        sysUser.setId(param.getId());
        sysUser.setEditTime(new Date().getTime());
        sysUserMapper.updateById(sysUser);
        return Result.success("ok");
    }

    @Override
    public Result deleteSysUser(String id) {
        SysUser sysUser = sysUserMapper.selectById(id);
        //先判断是否是root用户，如果是则不能删除
        if (sysUser.getRole().equals(Constant.ROLE_ROOT.getvalue())){
            return Result.fail(ErrorCode.PERMISSION_ERROR.getCode(),ErrorCode.PERMISSION_ERROR.getMsg());
        }
        if (Strings.isBlank(id)){
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(),ErrorCode.PARAMS_ERROR.getMsg());
        }
        sysUserMapper.deleteById(id);
        return Result.success("ok");
    }

    @Override
    public Result updatePwd(SysUserParam param) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        String md5Pwd = DigestUtils.md5Hex(param.getOldPwd() + slat);
        SysUser sysUser = findUser(param.getUsername(), md5Pwd);
        if (sysUser==null){
            return Result.fail(ErrorCode.PWD_ERROR.getCode(),ErrorCode.PWD_ERROR.getMsg());
        }
        SysUser user = new SysUser();
        user.setId(param.getId());
        user.setPassword(DigestUtils.md5Hex(param.getPassword() + slat));
        sysUserMapper.updateById(user);
        return Result.success("ok");
    }

    @Override
    public Result personalUpdate(SysUserParam param) {
        if (isExistUserName(param.getUsername())){
            return Result.fail(ErrorCode.ACCOUNT_EXIST.getCode(),ErrorCode.ACCOUNT_EXIST.getMsg());
        }
        SysUser sysUser = new SysUser();
        sysUser.setUsername(param.getUsername());
        sysUser.setName(param.getName());
        sysUser.setPhone(param.getPhone());
        //设置用户默认为启用状态
        sysUser.setEditTime(new Date().getTime());
        sysUser.setId(param.getId());
        sysUserMapper.updateById(sysUser);
        SysUser user = sysUserMapper.selectById(param.getId());
        String token = JWTUtils.createToken(sysUser);
        SysUserVo sysUserVo = new SysUserVo();
        BeanUtils.copyProperties(user,sysUserVo);
        sysUserVo.setRole(Constant.getname(user.getRole()));
        return Result.success(sysUserVo);
    }

    /**
     * 判断是否存在该用户名账号
     * @param username
     * @return
     */
    private Boolean isExistUserName(String username){
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername,username);
        SysUser sysUser = sysUserMapper.selectOne(wrapper);
        if (sysUser==null){
            return false;
        }
        return true;
    }
}
